package com.example.aimultimodel.controller;

import com.example.aimultimodel.model.dto.ChatDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.Collections;

/**
 * 智谱AI控制器
 * <p>
 * 说明:
 * - 流式接口输出采用 OpenAI Chat Completions SSE 兼容格式:
 * 第一个分片: role=assistant, content="" 的空增量
 * 中间分片: delta.content 为模型返回的增量文本
 * 结束分片: finish_reason=stop, 空 delta
 * 最后一条发送: [DONE]
 * - 返回 Flux<String>，每条为一个 JSON 或 "[DONE]"，由 Spring 以 text/event-stream 发送
 * 避免直接序列化底层 ChatResponse(含 Duration 等类型)导致的序列化异常
 *
 * @author 18747
 */
@RestController
@RequestMapping("/zhiPuAi")
@Slf4j
public class ZhiPuAiController {

    private final ChatClient chatClient;

    public ZhiPuAiController(@Qualifier("zhiPuAiChatClient") ChatClient chatClientBuilder) {
        this.chatClient = chatClientBuilder;
    }


    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatResponse> stream(@RequestBody ChatDto dto) {
        log.info("收到聊天请求: {}", dto.getMessage());

        // 使用concat替代merge，确保业务流完全结束后才处理心跳
        return chatClient.prompt()
                .user(dto.getMessage())
                .stream()
                .chatResponse()
                .concatWith(Flux.interval(Duration.ofSeconds(5))
                        .map(tick -> createEmptyHeartbeatResponse())
                        .takeUntil(response -> {
                            // 添加逻辑来终止心跳流
                            return false; // 或者根据实际情况添加终止条件
                        }))
                .takeUntil(response -> {
                    // 检查业务流是否完成
                    if (response.getResults().isEmpty()) {
                        return false;
                    }
                    response.getResults().getFirst().getMetadata();
                    return "STOP".equals(response.getResults().getFirst().getMetadata().get("finishReason"));
                });
    }


    private ChatResponse createEmptyHeartbeatResponse() {
        return new ChatResponse(Collections.emptyList());
    }

    @PostMapping("/chat")
    public ResponseEntity<String> chat(@RequestBody ChatDto dto) {
        try {
            String response = chatClient.prompt()
                    .user(dto.getMessage())
                    .call()
                    .content();
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("聊天请求处理失败", e);
            return ResponseEntity.internalServerError().body("抱歉，处理您的请求时出现了错误。");
        }
    }
}